﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Text;
using Newtonsoft.Json;
using MvcApplication.Models.Log;
using MvcApplication.Models.ApiModel;
using System.Web.Security;
using MvcApplication.Models.Common;

namespace MvcApplication.Controllers
{
    public class PayController : ApiController
    {
        /// <summary>
        /// 微信支付回调
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult Index()
        {
            var httpContext = HttpContext.Current;

            StringBuilder builder = new StringBuilder();
            //接收从微信后台POST过来的数据
            System.IO.Stream s = httpContext.Request.InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            Log.Info("微信支付回调", builder.ToString());

            var model = JsonConvert.DeserializeObject<ResultNotifyModel>(builder.ToString());
            Log.Info("微信支付回调", model.down_trade_no);
            //HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
            //创建ResponseHandler实例
            //ResponseHandler resHandler = new ResponseHandler(context);
            //Log.Info("微信支付回调", resHandler.getAllParameters());

            #region 协议参数


            #endregion
            httpContext.Response.Write("success");
            return Ok(httpContext);
        }


        /// <summary>
        /// 线上支付（秒富统一下单接口）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult PayCreate([FromBody]FormPayCreateModel model)
        {
            //支付参数
            FormPayContentApiModel payModel = new FormPayContentApiModel();
            payModel.timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            payModel.version = "v46";
            payModel.pay_channel = "WECHAT";
            payModel.sub_appid_type = "MINI_PROGRAM";
            payModel.amount = (model.rechargeMoney * 100).ToString("0");
            payModel.sub_open_id = model.openId;
            payModel.dev_id = "设备终端号";
            payModel.oper_id = "操作员";
            payModel.app_id = "APPID";
            payModel.sub_appid = "小程序APPID";
            payModel.down_trade_no = Guid.NewGuid().ToString("N");
            payModel.subject = "支付标题";
            payModel.back_notify_url = "回调地址";
            payModel.undiscountable_amount = "0";
            payModel.busi_code = "门店号";
            //拼接支付参数
            string BodyContent = GetPayContent(payModel);
            //签名
            //string Sign = FormsAuthentication.HashPasswordForStoringInConfigFile((BodyContent + "&APP_SECRET=" + "密钥").ToString(), "MD5");
            string Sign = BaseHelp.MD5Encrypt(BodyContent + "&APP_SECRET=" + "密钥", HttpContext.Current.Request.ContentEncoding.BodyName);
            Log.Info("线上支付", Sign);
            Log.Info("线上支付BodyContent", BodyContent + "&APP_SECRET=" + "密钥");
            Log.Info("线上支付MD5Encrypt", BaseHelp.MD5Encrypt(BodyContent + "&APP_SECRET=" + "密钥", HttpContext.Current.Request.ContentEncoding.BodyName));

            string requestUrl = "http://open.guangfen.net/api/v46/pay/create?" + BodyContent + "&sign=" + Sign.ToUpper();
            string result = BaseHelp.DoGet(requestUrl);
            Log.Info("线上支付result", result);

            ResultPayApiModel resultModel = JsonConvert.DeserializeObject<ResultPayApiModel>(result);
            if (resultModel.code == 0)
            {
                return Json(resultModel.pay_info);
            }
            else
            {
                return Json(resultModel.msg);
            }
        }

        /// <summary>
        /// 支付参数
        /// </summary>
        /// <param name="cfdOpenID"></param>
        /// <param name="paymentMoney"></param>
        /// <returns></returns>
        private string GetPayContent(FormPayContentApiModel model)
        {
            //拼接参数串
            StringBuilder retData = new StringBuilder();
            //参数
            SortedDictionary<string, string> parameters = new SortedDictionary<string, string>();
            //公共参数
            //appid
            parameters.Add("app_id", model.app_id);
            //时间戳
            parameters.Add("timestamp", model.timestamp);
            //版本号
            parameters.Add("version", model.version);
            //门店号
            parameters.Add("store_code", model.busi_code);
            //订单金额（单位分，最小1）
            parameters.Add("amount", model.amount);
            //不可打折金额(单位分,最小1)
            if (!string.IsNullOrEmpty(model.undiscountable_amount))
            {
                parameters.Add("undiscountable_amount", model.undiscountable_amount);
            }
            //设备终端号
            if (!string.IsNullOrEmpty(model.dev_id))
            {
                parameters.Add("dev_id", model.dev_id);
            }
            //操作员
            if (!string.IsNullOrEmpty(model.oper_id))
            {
                parameters.Add("oper_id", model.oper_id);
            }
            //支付方式
            if (!string.IsNullOrEmpty(model.pay_channel))
            {
                parameters.Add("pay_channel", model.pay_channel);
            }
            //接入方订单编号
            if (!string.IsNullOrEmpty(model.down_trade_no))
            {
                parameters.Add("down_trade_no", model.down_trade_no);
            }
            //订单标题
            if (!string.IsNullOrEmpty(model.subject))
            {
                parameters.Add("subject", model.subject);
            }
            //自定义数据,原路返回,接入方自行扩展
            if (!string.IsNullOrEmpty(model.raw_data))
            {
                parameters.Add("raw_data", model.raw_data);
            }
            //回调地址
            if (!string.IsNullOrEmpty(model.back_notify_url))
            {
                parameters.Add("back_notify_url", model.back_notify_url);
            }
            //小程序appid
            if (!string.IsNullOrEmpty(model.sub_appid))
            {
                parameters.Add("sub_appid", model.sub_appid);
            }
            //appid类型（MINI_PROGRAM是小程序
            //SUBSCRIPTION是微信公众号或者支付宝服务窗）
            if (!string.IsNullOrEmpty(model.sub_appid_type))
            {
                parameters.Add("sub_appid_type", model.sub_appid_type);
            }
            //openid
            if (!string.IsNullOrEmpty(model.sub_open_id))
            {
                parameters.Add("sub_open_id", model.sub_open_id);
            }

            //如果需要POST数据     
            if (!(parameters == null || parameters.Count == 0))
            {
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        retData.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        retData.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
            }
            return retData.ToString();
        }
    }
}
